"""工具函数模块"""

import re
from typing import Optional, List, Dict, Any
from datetime import datetime, timedelta
from nonebot.adapters.onebot.v11 import Message, MessageSegment
from .config import config


def parse_at_message(message: str) -> Optional[str]:
    """解析@消息，提取用户ID"""
    # 匹配 [CQ:at,qq=123456] 格式
    at_pattern = r'\[CQ:at,qq=(\d+)\]'
    match = re.search(at_pattern, message)
    if match:
        return match.group(1)
    return None


def format_ranking_text(records: List[Dict[str, Any]], period: str = "today") -> str:
    """格式化排行榜文本"""
    if not records:
        return "暂无数据"
    
    period_names = {
        "today": "今日",
        "yesterday": "昨日",
        "week": "本周",
        "month": "本月",
        "year": "今年",
        "total": "总"
    }
    
    period_name = period_names.get(period, "今日")
    result = f"🏆 {period_name}发言排行榜\n\n"
    
    total_messages = sum(record.get('count', 0) for record in records)
    
    for i, record in enumerate(records, 1):
        username = record.get('username', record.get('user_id', '未知用户'))
        count = record.get('count', 0)
        
        if config.message_counter_show_percentage and total_messages > 0:
            percentage = (count / total_messages) * 100
            result += f"{i}. {username}: {count} 条 ({percentage:.1f}%)\n"
        else:
            result += f"{i}. {username}: {count} 条\n"
    
    if config.message_counter_show_time:
        result += f"\n📅 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    
    return result.strip()


def get_time_range(period: str) -> tuple[datetime, datetime]:
    """获取时间范围"""
    now = datetime.now()
    today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    
    if period == "today":
        return today_start, now
    elif period == "yesterday":
        yesterday_start = today_start - timedelta(days=1)
        return yesterday_start, today_start
    elif period == "week":
        # 本周开始（周一）
        week_start = today_start - timedelta(days=now.weekday())
        return week_start, now
    elif period == "month":
        # 本月开始
        month_start = today_start.replace(day=1)
        return month_start, now
    elif period == "year":
        # 今年开始
        year_start = today_start.replace(month=1, day=1)
        return year_start, now
    else:
        # 默认返回今日
        return today_start, now


def is_valid_group_message(group_id: str, user_id: str) -> bool:
    """检查是否为有效的群消息"""
    # 检查群组白名单
    if config.message_counter_group_whitelist:
        if group_id not in config.message_counter_group_whitelist:
            return False
    
    # 检查群组黑名单
    if config.message_counter_group_blacklist:
        if group_id in config.message_counter_group_blacklist:
            return False
    
    # 检查用户黑名单
    if config.message_counter_user_blacklist:
        if user_id in config.message_counter_user_blacklist:
            return False
    
    return True


def safe_get_user_info(bot, user_id: str, group_id: str = None) -> Dict[str, str]:
    """安全获取用户信息"""
    try:
        # 这里应该调用bot的API获取用户信息
        # 由于是异步函数，这里只返回基本信息
        return {
            'user_id': user_id,
            'username': f'用户{user_id}',  # 默认用户名
            'group_id': group_id or ''
        }
    except Exception:
        return {
            'user_id': user_id,
            'username': f'用户{user_id}',
            'group_id': group_id or ''
        }


def safe_get_group_info(bot, group_id: str) -> Dict[str, str]:
    """安全获取群组信息"""
    try:
        # 这里应该调用bot的API获取群组信息
        return {
            'group_id': group_id,
            'group_name': f'群聊{group_id}'  # 默认群名
        }
    except Exception:
        return {
            'group_id': group_id,
            'group_name': f'群聊{group_id}'
        }


def format_time_period(period: str) -> str:
    """格式化时间段名称"""
    period_map = {
        'today': '今日',
        'yesterday': '昨日', 
        'week': '本周',
        'month': '本月',
        'year': '今年',
        'total': '总计'
    }
    return period_map.get(period, '今日')


def calculate_percentage(count: int, total: int) -> float:
    """计算百分比"""
    if total == 0:
        return 0.0
    return (count / total) * 100


def truncate_text(text: str, max_length: int = 50) -> str:
    """截断文本"""
    if len(text) <= max_length:
        return text
    return text[:max_length-3] + "..."


def is_bot_message(user_id: str, bot_id: str) -> bool:
    """检查是否为机器人消息"""
    return user_id == bot_id


def extract_plain_text(message: Message) -> str:
    """提取消息的纯文本内容"""
    return message.extract_plain_text().strip()


def parse_command_args(args_text: str) -> Dict[str, Any]:
    """解析命令参数"""
    result = {
        'limit': config.message_counter_default_limit,
        'period': 'today',
        'target_user': None
    }
    
    if not args_text:
        return result
    
    # 解析数量参数
    number_match = re.search(r'(\d+)', args_text)
    if number_match:
        result['limit'] = min(int(number_match.group(1)), 50)
    
    # 解析时间参数
    if any(keyword in args_text for keyword in ['昨日', 'yesterday']):
        result['period'] = 'yesterday'
    elif any(keyword in args_text for keyword in ['本周', 'week']):
        result['period'] = 'week'
    elif any(keyword in args_text for keyword in ['本月', 'month']):
        result['period'] = 'month'
    elif any(keyword in args_text for keyword in ['今年', 'year']):
        result['period'] = 'year'
    elif any(keyword in args_text for keyword in ['总', 'total']):
        result['period'] = 'total'
    
    return result


def format_user_card(username: str, user_id: str, stats: Dict[str, int], rankings: Dict[str, int]) -> str:
    """格式化用户信息卡片"""
    result = f"📊 {username} 的发言统计\n\n"
    
    periods = [
        ('今日', 'today'),
        ('昨日', 'yesterday'),
        ('本周', 'week'),
        ('本月', 'month'),
        ('今年', 'year'),
        ('总计', 'total')
    ]
    
    for period_name, period_key in periods:
        count = stats.get(period_key, 0)
        rank = rankings.get(period_key)
        rank_text = f"#{rank}" if rank else "#-"
        result += f"{period_name}: {count} 条 {rank_text}\n"
    
    return result.strip()


def validate_config() -> bool:
    """验证配置是否有效"""
    try:
        # 检查必要的配置项
        if not hasattr(config, 'message_counter_enable'):
            return False
        
        # 检查数据库配置
        if not hasattr(config, 'message_counter_database_url'):
            return False
        
        return True
    except Exception:
        return False


def get_emoji_for_rank(rank: int) -> str:
    """根据排名获取对应的emoji"""
    if rank == 1:
        return "🥇"
    elif rank == 2:
        return "🥈"
    elif rank == 3:
        return "🥉"
    elif rank <= 10:
        return "🏅"
    else:
        return "📊"


def format_duration(seconds: int) -> str:
    """格式化时长"""
    if seconds < 60:
        return f"{seconds}秒"
    elif seconds < 3600:
        minutes = seconds // 60
        return f"{minutes}分钟"
    else:
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        return f"{hours}小时{minutes}分钟"


def is_command_message(message: str) -> bool:
    """检查是否为命令消息"""
    command_prefixes = ['/', '!', '.', '#']
    return any(message.startswith(prefix) for prefix in command_prefixes)


def clean_username(username: str) -> str:
    """清理用户名中的特殊字符"""
    if not username:
        return "未知用户"
    
    # 移除可能导致问题的字符
    cleaned = re.sub(r'[\r\n\t]', ' ', username)
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    
    return cleaned or "未知用户"